import { useState, useEffect } from 'react';
import { supabase } from '../lib/supabase';
import type { TableData } from '../types';

export function useSearch(query: string) {
  const [results, setResults] = useState<TableData[]>([]);
  const [loading, setLoading] = useState(false);
  const [page, setPage] = useState(1);

  const fetchResults = async (searchQuery: string, pageNum: number) => {
    setLoading(true);
    try {
      const { data, error } = await supabase
        .from('table_data')
        .select('*')
        .ilike('title', `%${searchQuery}%`)
        .range((pageNum - 1) * 10, pageNum * 10 - 1)
        .order('created_at', { ascending: false });

      if (error) throw error;
      
      if (pageNum === 1) {
        setResults(data);
      } else {
        setResults(prev => [...prev, ...data]);
      }
    } catch (error) {
      console.error('Error fetching results:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (query) {
      fetchResults(query, page);
    }
  }, [query, page]);

  const loadMore = () => setPage(prev => prev + 1);

  return { results, loading, loadMore };
}
